package hz.mobileproject.pda.model.attendancemanager.activity;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;

import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.StringUtils;
import com.blankj.utilcode.util.TimeUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.google.gson.reflect.TypeToken;

import org.greenrobot.eventbus.EventBus;
import org.xutils.view.annotation.ContentView;
import org.xutils.view.annotation.Event;
import org.xutils.view.annotation.ViewInject;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

import hz.mobileproject.pda.R;
import hz.mobileproject.pda.app.MainApp;
import hz.mobileproject.pda.entity.MessageEvent;
import hz.mobileproject.pda.listener.CustomNetCallBack;
import hz.mobileproject.pda.model.attendancemanager.bean.Rp_loadOutReportType;
import hz.mobileproject.pda.model.attendancemanager.bean.Rq_loadOutReportType;
import hz.mobileproject.pda.model.attendancemanager.bean.Rq_saveOutReport;
import hz.mobileproject.pda.network.Constance;
import hz.mobileproject.pda.ui.adapter.PopListViewAdapter;
import hz.mobileproject.pda.ui.base.BaseActivity;
import hz.mobileproject.pda.ui.view.CustomPopWindow;
import hz.mobileproject.pda.ui.view.datepicker.CustomDatePicker;
import hz.mobileproject.pda.utils.HttpRqUtils;

@ContentView(R.layout.activity_outgoing_apply)
public class OutgoingApplyActivity extends BaseActivity {
    @ViewInject(R.id.tv_outgoing_begin_time_s)
    private TextView tv_outgoing_begin_time_s;
    @ViewInject(R.id.tv_outgoing_end_time_s)
    private TextView tv_outgoing_end_time_s;
    @ViewInject(R.id.tv_outgoing_reason_s)
    private TextView tv_outgoing_reason_s;
    @ViewInject(R.id.et_outgoing_city)
    private EditText et_outgoing_city;
    @ViewInject(R.id.et_outgoing_remark)
    private EditText et_outgoing_remark;


    private List<Rp_loadOutReportType> mResonList;
    private Rp_loadOutReportType mSelectedReason;

    @Override
    protected void initData() {
        loadReasonList();
    }

    @Event({R.id.tv_outgoing_reason_s, R.id.tv_outgoing_begin_time_s, R.id.tv_outgoing_end_time_s, R.id.btn_submit})
    private void onViewClick(View v) {
        switch (v.getId()) {
            case R.id.tv_outgoing_reason_s:
                if (mResonList == null) {
                    ToastUtils.showShort("未获取到外出事由数据");
                    loadReasonList();
                    return;
                }
                List<String> stringList = new ArrayList<>();
                for (Rp_loadOutReportType reson : mResonList) {
                    stringList.add(reson.getName());
                }
                showPopWindow(stringList, tv_outgoing_reason_s);
                break;
            case R.id.tv_outgoing_begin_time_s:
                showDatePicker(tv_outgoing_begin_time_s);
                break;
            case R.id.tv_outgoing_end_time_s:
                showDatePicker(tv_outgoing_end_time_s);
                break;
            case R.id.btn_submit:
                submitOutgoingApply();
                break;
        }
    }

    /**
     * 加载事由选项
     */
    private void loadReasonList() {
        Rq_loadOutReportType rq = new Rq_loadOutReportType(0);
        HttpRqUtils.httpPost(Constance.BASE_URL + Constance.URL_OUTGOING_LOADOUTREPORTTYPE, rq, new CustomNetCallBack() {
            @Override
            public void onSuccessFromSer(int rtnCode, String rtnMsg, String data) {
                LogUtils.e(data);
                mResonList = mGson.fromJson(data, new TypeToken<ArrayList<Rp_loadOutReportType>>() {
                }.getType());
                if (mResonList == null || mResonList.size() <= 0) {
                    ToastUtils.showShort("外出事由数据为空");
                }
            }

            @Override
            public void onErrorFromSer(int rtnCode, String rtnMsg) {
                LogUtils.e(rtnCode + rtnMsg);
                ToastUtils.showShort("外出事由数据获取失败(" + rtnCode + "," + rtnMsg + ")");
            }

            @Override
            public void onErrorFromNet(Throwable ex, boolean isOnCallback) {
                LogUtils.e(ex.toString());
                ToastUtils.showShort("获取数据失败，请检查网络");
            }
        });
    }

    /**
     * 提交申请
     */
    private void submitOutgoingApply() {
        if (StringUtils.isEmpty(tv_outgoing_begin_time_s.getText())) {
            ToastUtils.showShort("请选择开始时间");
            return;
        }
        if (StringUtils.isEmpty(tv_outgoing_end_time_s.getText())) {
            ToastUtils.showShort("请选择结束时间");
            return;
        }
        if (StringUtils.isEmpty(tv_outgoing_reason_s.getText()) || mSelectedReason == null) {
            ToastUtils.showShort("请选择外出事由");
            return;
        }
        if (StringUtils.isEmpty(et_outgoing_city.getText())) {
            ToastUtils.showShort("请填写外出城市");
            return;
        }
        Rq_saveOutReport rq = new Rq_saveOutReport();
        rq.setCusNumber(MainApp.getInstance().getLoginUser().getCus_number() + "");
        rq.setPoliceCode(MainApp.getInstance().getLoginUser().getPolice_code());
        rq.setReason(mSelectedReason.getId() + "");
        rq.setStartDate(tv_outgoing_begin_time_s.getText().toString());
        rq.setEndDate(tv_outgoing_end_time_s.getText().toString());
        rq.setDirection(et_outgoing_city.getText().toString());
        rq.setHolidayType("");
        rq.setRemark(et_outgoing_remark.getText().toString());
        rq.setIsReceive("0");
        rq.setIsReturn("0");
        rq.setFlowTypeId(Rq_saveOutReport.FLOW_TYPE_ID_OUT_AND_LEAVE);
        HttpRqUtils.httpPost(Constance.BASE_URL + Constance.URL_OUTGOING_SAVEOUTREPORT, rq, new CustomNetCallBack() {
            @Override
            public void onSuccessFromSer(int rtnCode, String rtnMsg, String data) {
                LogUtils.e(data);
                ToastUtils.showShort("提交成功");
                EventBus.getDefault().post(new MessageEvent("OutgoingActivity.refreshData",""));
                OutgoingApplyActivity.this.finish();
            }

            @Override
            public void onErrorFromSer(int rtnCode, String rtnMsg) {
                LogUtils.e(rtnCode + rtnMsg);
                ToastUtils.showShort("提交失败(" + rtnCode + "," + rtnMsg + ")");
            }

            @Override
            public void onErrorFromNet(Throwable ex, boolean isOnCallback) {
                LogUtils.e(ex.toString());
                ToastUtils.showShort("提交失败失败，请检查网络");
            }
        });
    }


    /**
     * 弹出选择项popwindow
     *
     * @param
     * @param showAsDropDownView
     */
    private void showPopWindow(final List<String> stringList, final View showAsDropDownView) {
        if (stringList == null || stringList.size() <= 0) {
            return;
        }
        View contentView = LayoutInflater.from(this).inflate(R.layout.pop_custom_list, null);
        //处理popWindow 显示内容
        ListView listView = (ListView) contentView.findViewById(R.id.lv_dialog);
        PopListViewAdapter adapter = new PopListViewAdapter(this, stringList);
        adapter.setColor("#eeeeee", "#4084E4");
        listView.setAdapter(adapter);
        //创建并显示popWindow
        final CustomPopWindow mListPopWindow = new CustomPopWindow.PopupWindowBuilder(this)
                .setView(contentView)
                .size(showAsDropDownView.getWidth(), ViewGroup.LayoutParams.WRAP_CONTENT)//显示大小
                .create()
                .showAsDropDown(showAsDropDownView, 0, 10);
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                mListPopWindow.dissmiss();
                ((TextView) showAsDropDownView).setText(stringList.get(position));
                switch (showAsDropDownView.getId()) {
                    case R.id.tv_outgoing_reason_s://点击外出事由
                        mSelectedReason = mResonList.get(position);
                        break;
                }
            }
        });
    }


    private void showDatePicker(final TextView tv) {
        String selectTime = "";
        if (!StringUtils.isEmpty(tv.getText())) {
            selectTime = tv.getText().toString();
        } else {
            selectTime = TimeUtils.getNowString(new SimpleDateFormat("yyyy-MM-dd HH:mm"));
        }
        CustomDatePicker customDatePicker = new CustomDatePicker(this, new CustomDatePicker.ResultHandler() {
            @Override
            public void handle(String time) { // 回调接口，获得选中的时间
                tv.setText(time);
            }
        }, "1968-01-01 00:00", "2068-01-01 00:00"); // 初始化日期格式请用：yyyy-MM-dd HH:mm，否则不能正常运行
        customDatePicker.showSpecificTime(true); // 不显示时和分
        customDatePicker.setIsLoop(false); // 不允许循环滚动
        customDatePicker.show(selectTime);
    }
}
